/**
 * 险金档案申请
 */

import React, { useRef, useState, useEffect } from 'react';
import { Form, Input, Spin, Row, Col, DatePicker, message } from 'antd';
import { withRouter } from 'umi';
import { useMeasure, useMount } from 'react-use';
import classNames from 'classnames';
import keyBy from 'lodash/keyBy';
import moment from 'moment';

import { processService } from '@/services/salaryManage/process';
import { isSuccess } from '@/utils/request';
import DateFormatter from '@/components/DateFormatter';
import If from '@/components/If';

import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';

import { OrganizationNameConnect } from '@/pages/SalaryManage/components/OrganizationName';
import { queryBaseSettingInfo } from '@/services/salaryManage/salaryCalculate';
import { defaultFormatResult } from '@/hooks';
import BaseSettingContext from './BaseSettingContext';
import CompareItem from './CompareItem';
import OrganizationNameItem from './OrganizationNameItem';
import style from './index.less';

const { Item } = Form;

const getWidthMapper = width => {
    let widthMapper;

    // 一列最小408计算
    if (width < 816) {
        widthMapper = { normal: 24 };
    } else if (width < 1224) {
        widthMapper = { normal: 12 };
    } else if (width < 1624) {
        widthMapper = { normal: 8 };
    } else {
        widthMapper = { normal: 6 };
    }

    return widthMapper;
};

const SalarySetSdlApply = ({ form, formValueMap, dataSource, location }) => {
    const [loading, setLoading] = useState(false);
    const [ref, { width }] = useMeasure();
    const [baseSetting, setBaseSetting] = useState({});
    const widthMapper = getWidthMapper(width);

    const childConfig = dataSource?.children?.length > 0 ? dataSource.children : [];
    const childrenConfigMap = keyBy(childConfig, 'formId');
    const summaryConfig = childrenConfigMap.summary;
    const organizationNameConfig = childrenConfigMap.organizationName;
    const uploadConfig = childrenConfigMap.OssUploadFiles;
    // 如果流程附件配置为只读时，后台不会返回配置信息，就无需显示
    if (uploadConfig) {
        uploadConfig.uploadProps.disabled = uploadConfig.options.disabled;
    }

    const { getFieldDecorator } = form;
    const [pageModel, setPageModel] = useState(formValueMap?.applyModel || {});
    const [initialEffectTime, setInitialEffectTime] = useState(null);
    const [currentHoverRow, setCurrentHoverRow] = useState(null);
    const [currentSelectedRow, setCurrentSelectedRow] = useState(null);
    const before = pageModel?.dataBefore || [];
    const after = pageModel?.dataAfter || [];
    const leftList = before || [];
    const rightList = after || [];
    const leftRef = useRef();
    const rightRef = useRef();

    const { sdlId } = location.query;
    const isApply = !!sdlId;
    // 由于在申请界面或审批详情界面限定了90%的宽度(表单设计页没有限定)，而且我们要100%，所在增加了负值的marginRight
    const extraRight = isApply || formValueMap;

    const setFieldValue = (filedName, fieldValue) => {
        setPageModel({ ...pageModel, [filedName]: fieldValue });
    };

    const onEffectTime = (expireMoment, formatExpireTime) => {
        setFieldValue('effectTime', formatExpireTime);
    };

    // 以下代码保存左右滚动同步
    useMount(() => {
        const leftTableBody =
            leftRef.current.querySelector('.ant-table-body') || leftRef.current.querySelector('.ant-table-content');

        const rightTableBody =
            rightRef.current.querySelector('.ant-table-body') || rightRef.current.querySelector('.ant-table-content');

        if (leftTableBody && rightTableBody) {
            const leftScrollFn = () => {
                if (leftTableBody.scrollLeft !== rightTableBody.scrollLeft) {
                    rightTableBody.scrollLeft = leftTableBody.scrollLeft;
                }
            };

            const rightScrollFn = () => {
                if (leftTableBody.scrollLeft !== rightTableBody.scrollLeft) {
                    leftTableBody.scrollLeft = rightTableBody.scrollLeft;
                }
            };

            leftTableBody.addEventListener('scroll', leftScrollFn);
            rightTableBody.addEventListener('scroll', rightScrollFn);

            return () => {
                leftTableBody.removeEventListener('scroll', leftScrollFn);
                rightTableBody.removeEventListener('scroll', rightScrollFn);
            };
        }
        return null;
    });

    useMount(async () => {
        // 如果是发起申请界面
        if (isApply) {
            setLoading(true);
            try {
                const response = await processService.queryNextStepSdl({ sdlId });
                setLoading(false);

                if (isSuccess(response)) {
                    setPageModel(response.data);
                    setInitialEffectTime(response.data?.effectTime ? moment(response.data?.effectTime) : null);
                } else {
                    message.error(response.msg);
                }
            } catch (e) {
                setLoading(false);
            }
        } else {
            setInitialEffectTime(pageModel?.effectTime ? moment(pageModel?.effectTime) : null);
        }
    });

    useEffect(() => {
        if (formValueMap?.applyModel) {
            setPageModel(formValueMap?.applyModel);
        }
    }, [formValueMap]);

    useEffect(() => {
        if (pageModel.organizationCode) {
            queryBaseSettingInfo(pageModel.organizationCode)
                .then(defaultFormatResult.formatResult)
                .then(baseSettingData => {
                    setBaseSetting(baseSettingData);
                });
        }
    }, [pageModel.organizationCode]);

    return (
        <Spin spinning={loading}>
            <BaseSettingContext.Provider value={{ contextState: baseSetting, setContextState: setBaseSetting }}>
                <div className={classNames(style.skillsDevelopmentTaxApply, { [style.extraRight]: extraRight })}>
                    {getFieldDecorator('applyModel', { initialValue: pageModel })(<Input type="hidden" />)}

                    {/* 行政机构 */}
                    <OrganizationNameItem
                        form={form}
                        formValueMap={formValueMap}
                        organizationNameConfig={organizationNameConfig}
                        organizationCode={pageModel?.organizationCode}
                    />

                    {/* 流程名称 */}
                    {summaryConfig ? (
                        <Form.Item
                            label={summaryConfig.label}
                            key={summaryConfig.formId}
                            style={{ display: summaryConfig?.inRenderDom === false ? 'none' : 'block' }}
                        >
                            {getFieldDecorator(summaryConfig?.formId, {
                                rules: summaryConfig?.rules,
                                initialValue:
                                    formValueMap?.[summaryConfig.formId] ?? summaryConfig?.options?.initialValue
                            })(<AutoRenderComponent form={form} config={summaryConfig} />)}
                        </Form.Item>
                    ) : null}

                    <div>
                        <div ref={ref} style={{ maxWidth: 1224 }} className={style.ml8}>
                            <If condition={pageModel?.organizationCode || formValueMap?.applicationNo}>
                                <Row>
                                    <If condition={pageModel?.organizationCode}>
                                        <Col span={widthMapper.normal}>
                                            <Form.Item label="行政机构：" className={classNames(style.mb0)}>
                                                <OrganizationNameConnect
                                                    organizationCode={pageModel?.organizationCode}
                                                />
                                            </Form.Item>
                                        </Col>
                                    </If>
                                    <If condition={formValueMap?.applicationNo}>
                                        <Col span={widthMapper.normal}>
                                            <Form.Item label="申请编号：" className={classNames(style.mb0)}>
                                                {formValueMap?.applicationNo}
                                            </Form.Item>
                                        </Col>
                                    </If>
                                </Row>
                            </If>

                            <Row>
                                <Col span={widthMapper.normal}>
                                    <Item label="申请人员：" className={classNames(style.mb0)}>
                                        <EmptyPlaceHolder value={pageModel?.approveName} />
                                    </Item>
                                </Col>
                                <Col span={widthMapper.normal}>
                                    <Item label="所在部门：" className={classNames(style.mb0)}>
                                        <EmptyPlaceHolder value={pageModel?.department} />
                                    </Item>
                                </Col>
                                {pageModel?.tableObject ? <Col span={widthMapper.normal}>
                                    <Item label="表格名称：" className={classNames(style.mb0)}>
                                        <EmptyPlaceHolder value={pageModel?.tableObject} />
                                    </Item>
                                </Col> : null}
                                <Col span={widthMapper.normal}>
                                    <Item label="申请日期：" className={classNames(style.mb0)}>
                                        <DateFormatter value={pageModel?.approveDate} pattern="YYYY-MM-DD" />
                                    </Item>
                                </Col>
                                <Col span={widthMapper.normal}>
                                    <Item label="生效年月：" className={classNames(style.mb0)}>
                                        {isApply
                                            ? getFieldDecorator('effectTime', {
                                                  initialValue: initialEffectTime,
                                                  rules: [
                                                      {
                                                          required: true,
                                                          message: '请填写生效年月'
                                                      }
                                                  ]
                                              })(
                                                  <DatePicker.MonthPicker
                                                      onChange={onEffectTime}
                                                      disabled={!isApply}
                                                      disabledDate={currentDate =>
                                                          initialEffectTime
                                                              ? initialEffectTime.isAfter(currentDate)
                                                              : false
                                                      }
                                                  />
                                              )
                                            : pageModel?.effectTime}{' '}
                                        起
                                    </Item>
                                </Col>
                                <Col span={widthMapper.normal}>
                                    <Item label="重要提示：" className={classNames(style.mb0)}>
                                        {!isApply ? (
                                            <span className={style.info}>
                                                <EmptyPlaceHolder value={pageModel.remark} />
                                            </span>
                                        ) : (
                                            <Input
                                                maxLength={200}
                                                onChange={e => setFieldValue('remark', e.target.value)}
                                                disabled={!isApply}
                                                value={pageModel.remark}
                                            />
                                        )}
                                    </Item>
                                </Col>
                            </Row>
                        </div>
                        <Row type="flex" gutter={24} className="compare">
                            <Col className="compare-item" span={12}>
                                <h6 className="compare-item-title">变更前</h6>
                                <div ref={leftRef} className="compare-item-body">
                                    <CompareItem
                                        dataSource={leftList}
                                        showCompareEffect={false}
                                        comparePosition="left"
                                        hoverRow={currentHoverRow}
                                        selectedRow={currentSelectedRow}
                                        setCurrentHoverRow={setCurrentHoverRow}
                                        setCurrentSelectedRow={setCurrentSelectedRow}
                                    />
                                </div>
                            </Col>
                            <Col className="compare-item" span={12}>
                                <h6 className="compare-item-title">变更后</h6>
                                <div ref={rightRef} className="compare-item-body">
                                    <CompareItem
                                        dataSource={rightList}
                                        showCompareEffect
                                        comparePosition="right"
                                        hoverRow={currentHoverRow}
                                        selectedRow={currentSelectedRow}
                                        setCurrentHoverRow={setCurrentHoverRow}
                                        setCurrentSelectedRow={setCurrentSelectedRow}
                                    />
                                </div>
                            </Col>
                        </Row>
                        {uploadConfig ? (
                            <Row>
                                <Form.Item label="附件：" className={classNames(style.mb0, style.flex)}>
                                    {getFieldDecorator(uploadConfig?.formId, {
                                        rules: uploadConfig?.rules,
                                        initialValue: formValueMap?.[uploadConfig.formId] ?? uploadConfig.initialValue
                                    })(<AutoRenderComponent form={form} config={uploadConfig} />)}
                                </Form.Item>
                            </Row>
                        ) : null}
                    </div>
                </div>
            </BaseSettingContext.Provider>
        </Spin>
    );
};

export default withRouter(React.memo(SalarySetSdlApply));
